package cz.muni.fi.pa036.kiss.daoimpl;

import cz.muni.fi.pa036.kiss.Entity.BilancePlateb;
import cz.muni.fi.pa036.kiss.Entity.Student;
import cz.muni.fi.pa036.kiss.dao.BilancePlatebDAO;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author peter
 */
public class BilancePlatebDAOImpl implements BilancePlatebDAO{

    @PersistenceContext
    private EntityManager em;
    
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }

    @Override
    public void create(BilancePlateb bilance) {
        if (bilance == null) {
            throw new IllegalArgumentException("bilance is null");
        }
        if (bilance.getId() != null) {
            throw new IllegalArgumentException("bilance.id is not null");
        }

        em.persist(bilance);
    }

    @Override
    public BilancePlateb get(Long id) {
        if (id == null) {
            throw new IllegalArgumentException("null id");
        }
        BilancePlateb bilancePlateb = em.find(BilancePlateb.class, id);
        return bilancePlateb;
    }

    @Override
    public void update(BilancePlateb bilance) {
        if (bilance == null) {
            throw new IllegalArgumentException("bilance is null");
        }
        if (bilance.getId() == null) {
            throw new IllegalArgumentException("bilance.id is null");
        }
        
        em.merge(bilance);
    }

    @Override
    public void remove(BilancePlateb bilance) {
        if (bilance == null) {
            throw new IllegalArgumentException("bilance is null");
        }
        if (bilance.getId() == null) {
            throw new IllegalArgumentException("bilance.id is null");
        }
        BilancePlateb c = em.find(BilancePlateb.class, bilance.getId());
        em.remove(c);
    }

    @Override
    public List<BilancePlateb> findAll() {
        Query query = em.createQuery("SELECT c FROM BilancePlateb c");
        List<BilancePlateb> results = query.getResultList();

        return results;
    }

    @Override
    public List<BilancePlateb> findByStudent(Student student) {
        if (student == null) {
            throw new IllegalArgumentException("student is null");
        }
        if (student.getId() == null) {
            throw new IllegalArgumentException("student's id is null");
        }

        Query query;
        query = em.createQuery("SELECT o FROM BilancePlateb o WHERE o.student.id = :id");
        query.setParameter("id", student.getId());

        List<BilancePlateb> results = query.getResultList();
        return results;
        
//        TypedQuery<BilancePlateb> tq = em.createQuery("SELECT o FROM BilancePlateb o WHERE o.student.id = :id", BilancePlateb.class);
//        tq.setParameter("id", student.getId());
//
//        return tq.getResultList();
    }
    
}
